import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { clearToken } from '@/store/authSlice';
import { getUserInfo } from '@/apis/getUserInfo';
import { useNotification } from '@/context/NotificationContext'; // 新增这行
import {
  Drawer,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Divider,
  Typography,
  Box
} from '@mui/material';
import {
  Home,
  Person,
  Search,
  ShoppingCart,
  ExitToApp,
  Assignment,
  Headset,
  Settings,
  Inventory,
  Notifications
} from '@mui/icons-material';

const Sidebar = ({ open, onClose }) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [userRole, setUserRole] = useState(null);
  const { logout: notificationLogout } = useNotification(); // 新增这行

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const userInfo = await getUserInfo();
        setUserRole(userInfo.role);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    fetchUserInfo();
  }, []);

  const handleLogout = () => {
    dispatch(clearToken());
    notificationLogout(); // 新增这行
    navigate('/login');
  };
  
 

  const menuItems = [
    {
      category: '快捷操作',
      items: [
        { name: '首页', icon: <Home />, action: () => navigate('/') },
        { name: '个人中心', icon: <Person />, action: () => navigate('/profile') },
        { name: '搜索', icon: <Search />, action: () => navigate('/search') },
        { name: '购物车', icon: <ShoppingCart />, action: () => navigate('/cart') },
      ],
    },
    {
      category: '订单与服务',
      items: [
        { name: '我的订单', icon: <Assignment />, action: () => navigate('/orders') },
        { name: '客户服务', icon: <Headset />, action: () => navigate('/customer-service') },
      ],
    },
  ];
  
  if (userRole === 1) {
    menuItems.push({
      category: '后台管理',
      items: [
        { name: '商品管理', icon: <Inventory />, action: () => navigate('/admin/products') },
        { name: '通知管理', icon: <Notifications />, action: () => navigate('/admin/notifications') },
        { name: '系统设置', icon: <Settings />, action: () => navigate('/admin/settings') },
      ],
    });
  }

  menuItems.push({
    category: '账户',
    items: [
      { name: '退出登录', icon: <ExitToApp />, action: handleLogout },
    ],
  });

  return (
    <Drawer 
      anchor="left" 
      open={open} 
      onClose={onClose}
      variant="temporary"
      disableScrollLock={true}
      ModalProps={{
        keepMounted: true,
      }}
    >
      <Box 
        sx={{ width: 250 }} 
        role="presentation" 
      >
        {menuItems.map((section, index) => (
          <React.Fragment key={section.category}>
            <List>
              <ListItem>
                <Typography variant="subtitle1" color="primary">
                  {section.category}
                </Typography>
              </ListItem>
              {section.items.map((item) => (
                <ListItemButton
                  key={item.name}
                  onClick={() => {
                    item.action();
                    onClose();
                  }}
                >
                  <ListItemIcon>{item.icon}</ListItemIcon>
                  <ListItemText primary={item.name} />
                </ListItemButton>
              ))}
            </List>
            {index < menuItems.length - 1 && <Divider />}
          </React.Fragment>
        ))}
      </Box>
    </Drawer>
  );
};

export default Sidebar;